~{define "components/contextMenu"}~
<style>
    .context-menu {
        position: absolute;
        background-color: white;
        border: 1px solid #ccc;
        box-shadow: 2px 2px 12px rgba(0, 0, 0, 0.2);
        display: none;
        z-index: 1000;
        padding-left: 0;
    }

    .context-menu.active {
        display: block;
    }

    .context-menu li {
        list-style: none;
        padding: 8px 12px;
        cursor: pointer;
    }

    .context-menu li:hover {
        background-color: #eee;
    }

    .context-menu li[divider] {
        /* color: #666; */
        border-top: 1px solid #ccc;
    }
</style>
<script>
    Vue.component('context-menu', {
        template: `
            <div @contextmenu.prevent="showMenu($event)">
                <slot>Right-click here</slot>
                <ul @click="action" class="context-menu" :class="{ active: isMenuVisible }" :style="{ top: menuPosition.y + 'px', left: menuPosition.x + 'px' }">
                    <slot name="menu"></slot>
                </ul>
            </div>
        `,
        data() {
            return {
                isMenuVisible: false,
                menuPosition: { x: 0, y: 0 },
            };
        },
        methods: {
            showMenu(event) {
                this.menuPosition.x = event.clientX;
                this.menuPosition.y = event.clientY;
                this.isMenuVisible = true;
                document.addEventListener('click', this.hideMenu);
            },
            hideMenu() {
                this.isMenuVisible = false;
                document.removeEventListener('click', this.hideMenu);
            },
            action(e) {
                console.log(e.target.dataset.item)
                if (e.target.dataset.item) {
                    this.$emit('menu-click', e.target.dataset.item);
                }
                this.hideMenu();
            }
        }
    });
</script>
~{end}~

<!-- 使用实例
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vue 2 Context Menu Component</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
</head>
~{template "components/contextMenu" .}~

<body>
    <div id="app">
        <context-menu @menu-click="onMenuClick">
            <template v-slot:menu>
                <li>Option 1</li>
                <li data-item="$emit('menu-click', 'Option 2')" divider>Option 2</li>
                <li data-item="$emit('menu-click', 'Option 3')">Option 3</li>
            </template>
        </context-menu>
    </div>

    <script>

        new Vue({
            el: '#app',
            methods: {
                onMenuClick(option) {
                    alert('You selected ' + option);
                }
            }
        });
    </script>
</body>

</html> -->